import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_type_config.dart';
import 'package:largefriends/pages/lf_feedback/lf_feedback_logic.dart';
import 'package:largefriends/res.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_fonts.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/res/lf_widget_ext.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/utils/lf_keyboard.dart';
import 'package:largefriends/widgets/category_widget.dart';
import 'package:largefriends/widgets/lf_app_bar.dart';
import 'package:largefriends/widgets/lf_button.dart';
import 'package:largefriends/widgets/lf_email_cells.dart';
import 'package:largefriends/widgets/lf_single_picker.dart';
import 'package:largefriends/widgets/lf_text_filed.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class LfFeedbackPage extends StatefulWidget {
  const LfFeedbackPage({super.key});

  @override
  State<LfFeedbackPage> createState() => _LfFeedbackPageState();
}

class _LfFeedbackPageState extends State<LfFeedbackPage> {
  final logic = Get.put(LfFeedbackLogic());
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: lfAppBar(
            title: strFeedback.tr,
            leadingCallback: () {
              Get.back();
            },
          ),
          resizeToAvoidBottomInset: true,
          body: Stack(
            children: [
              Positioned.fill(
                child: Obx(
                  () {
                    var y = 1.h;
                    if (logic.email.isNotEmpty && logic.emailFocused.isTrue) {
                      y = 50.h;
                    }
                    return Padding(
                      padding:
                          EdgeInsets.only(bottom: y, left: 16.w, right: 16.w),
                      child: CustomScrollView(
                        physics: const BouncingScrollPhysics(),
                        slivers: [
                          10.h.sbh.sliverBox,
                          LfCategoryWidget(
                            title: strTopicSubject.tr,
                            child: InkWell(
                              onTap: () {
                                if (isShowSoftKeyboard()) {
                                  closeSoftKeyboard();
                                }
                                showLfSinglePicker(
                                  configTypeEnum: LfConfigTypeEnum.feedback,
                                  value: logic.topic.value,
                                  title: strTopicSubject.tr,
                                  isDismissible: true,
                                  saveCallback: (value) {
                                    logic.topic.value = value;
                                  },
                                );
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    vertical: 10.h, horizontal: 10.h),
                                decoration: BoxDecoration(
                                    color: color8F8F8F,
                                    borderRadius: 5.r.radius),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Expanded(
                                      child: Obx(
                                        () => Text(
                                          logic.topic.value == 0
                                              ? strPleaseChoose.tr
                                              : TypeConfig().getValueByKey(
                                                  LfConfigTypeEnum.feedback,
                                                  logic.topic.value,
                                                ),
                                          style: logic.topic.value == 0
                                              ? lfHintStyle
                                              : lfTextStyle(
                                                  sp: 14.sp,
                                                  color: colorFEFEFE,
                                                ),
                                        ),
                                      ),
                                    ),
                                    const Icon(Icons.keyboard_arrow_down)
                                  ],
                                ),
                              ),
                            ),
                          ).sliverBox,
                          LfCategoryWidget(
                              title: "${strContent.tr}*",
                              child: LfTextFiled(
                                textEditingController: logic.contentController,
                                isPassword: false,
                                maxLine: 4,
                                minLine: 4,
                                // fillColor: colorFEFEFE,
                                hintText: strFeedbackContentTip.tr,
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(500)
                                ],
                                onChanged: (value) {
                                  logic.content.value = value;
                                },
                              )).sliverBox,
                          LfCategoryWidget(
                            title: logic.authService.loggedIn()
                                ? strYourEmail.tr
                                : "${strYourEmail.tr}*",
                            child: LfTextFiled(
                              textEditingController: logic.emailController,
                              isPassword: false,
                              hintText: strYourEmail.tr,
                              focusNode: logic.emailFocusNode,
                              keyboardType: TextInputType.emailAddress,
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(
                                    RegExp('[A-Za-z0-9_@.]')),
                              ],
                              onChanged: (value) {
                                logic.email.value = value;
                              },
                            ),
                          ).sliverBox,
                          LfCategoryWidget(
                            title: strYourPhoneNumber.tr,
                            child: LfTextFiled(
                              textEditingController:
                                  logic.phoneNumberController,
                              isPassword: false,
                              hintText: strOptional.tr,
                              focusNode: logic.phoneFocusNode,
                              keyboardType: TextInputType.phone,
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(
                                    RegExp('[0-9-+]')),
                              ],
                              onChanged: (value) {
                                logic.phoneNumber.value = value;
                              },
                            ),
                          ).sliverBox,
                          LfCategoryWidget(
                            title: strScreenshots.tr,
                            child: Column(
                              children: [
                                Text(
                                  strScreenshotsTip.tr,
                                  textAlign: TextAlign.center,
                                  style: lfTextStyle(
                                      sp: 15.sp,
                                      fontFamily: fontRegular,
                                    color: color514F62
                                  ),
                                ),
                                10.h.sbh,
                                SizedBox(
                                  height: 100.h,
                                  child: Obx(
                                    () => GridView.builder(
                                      physics:
                                          const NeverScrollableScrollPhysics(),
                                      gridDelegate:
                                          const SliverGridDelegateWithFixedCrossAxisCount(
                                        crossAxisCount: 3,
                                        crossAxisSpacing: 10.0,
                                        mainAxisSpacing: 10.0,
                                      ),
                                      itemCount: logic.photos.length >= 3
                                          ? 3
                                          : logic.photos.length + 1,
                                      itemBuilder: (context, index) {
                                        if (logic.photos.length < 3 &&
                                            index == logic.photos.length) {
                                          return _getGridSpace();
                                        } else {
                                          return _getGridChild(
                                            logic.photos[index],
                                          );
                                        }
                                      },
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ).sliverBox,
                          15.h.sbh.sliverBox,
                          Text(
                            strFeedbackRespondTp.tr,
                            textAlign: TextAlign.center,
                            style: lfTextStyle(
                              sp: 15.sp,
                              fontFamily: fontRegular,color: color514F62
                            ),
                          ).sliverBox,
                          10.h.sbh.sliverBox,
                          10.h.sliverBox,
                          Text(
                            strContactEmailTip.tr,
                            textAlign: TextAlign.center,
                            style: lfTextStyle(
                              sp: 15.sp,
                              fontFamily: fontRegular,
                              color: color514F62,
                            ),
                          ).sliverBox,
                          5.h.sliverBox,
                          InkWell(
                            onTap: () {
                              final Uri telLaunchUri = Uri(
                                scheme: 'mailto',
                                path: "support@largefriends.com",
                                query: encodeQueryParameters({
                                  'subject': TypeConfig().getValueByKey(
                                    LfConfigTypeEnum.feedback,
                                    logic.topic.value,
                                  )
                                }),
                              );
                              launchUrl(telLaunchUri);
                            },
                            child: Text(
                              "support@largefriends.com", //不确定邮箱

                              textAlign: TextAlign.center,
                              style: lfTextStyle(
                                sp: 15.sp,
                                fontFamily: fontMedium,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                          ).sliverBox,
                          20.h.sliverBox,
                          Obx(
                            () => LfButton(
                              enabled: logic.enableSendFeedback,
                              text: strSend.tr,
                              onPress: () {
                                logic.sendFeedback();
                              },
                            ),
                          ).sliverBox,
                          20.h.sliverBox,
                        ],
                      ),
                    );
                  },
                ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Obx(() {
                  if (logic.email.isNotEmpty && logic.emailFocused.isTrue) {
                    return SizedBox(
                      height: 50,
                      width: MediaQuery.of(context).size.width,
                      child: ListView(
                        padding: EdgeInsets.zero,
                        scrollDirection: Axis.horizontal,
                        children: getEmailCells(selected: (value) {
                          var currentInput = logic.emailController.text;
                          var index = currentInput.indexOf("@");
                          if (index > 0) {
                            currentInput = currentInput.substring(0, index);
                          }
                          logic.emailController.text = "$currentInput$value";
                          logic.email.value = "$currentInput$value";
                          logic.emailController.selection =
                              TextSelection.fromPosition(
                            TextPosition(
                              offset: logic.emailController.text.length,
                              affinity: TextAffinity.downstream,
                            ),
                          );
                        }),
                      ),
                    );
                  } else {
                    return empty;
                  }
                }),
              )
            ],
          ),
        ),
        onWillPop: () async {
          Get.back();
          return false;
        });
  }

  String? encodeQueryParameters(Map<String, String> params) {
    return params.entries
        .map((e) =>
            "${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}")
        .join("&");
  }

  Widget _getGridSpace() {
    return InkWell(
      child: Container(
        decoration:
            BoxDecoration(color: color8F8F8F, borderRadius: 10.r.radius),
        alignment: Alignment.center,
        child: Icon(
          Icons.add,
          color: colorFF007F,
        ),
      ),
      onTap: () {
        logic.addPhoto();
      },
    );
  }

  Widget _getGridChild(AssetEntity file) {
    return LayoutBuilder(builder: (context, constant) {
      return SizedBox(
        width: constant.maxWidth,
        height: constant.maxHeight,
        child: Stack(
          children: [
            Positioned(
                child: ClipRRect(
              borderRadius: 10.r.radius,
              child: AssetEntityImage(
                file,
                isOriginal: false,
                fit: BoxFit.cover,
                width: constant.maxWidth,
                height: constant.maxHeight,
              ),
            )),
            Align(
              alignment: Alignment.topRight,
              child: InkWell(
                child: Container(
                  decoration:
                  BoxDecoration(color: color210215, shape: BoxShape.circle),
                  margin: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                  child: Icon(
                    Icons.close,
                    color: Colors.white,
                    size: 22.r,
                  ),
                ),
                onTap: () {
                  logic.photos.remove(file);
                },
              ),
            )
          ],
        ),
      );
    });
  }
}
